package unipi.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import unipi.database.ErrorCodes;
import unipi.database.User;
import unipi.helpers.LoginCookie;

public class UploadPicture  extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public UploadPicture()
	{
		super();
	}
	
	public void init() throws ServletException
	{
		
	
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		if(!LoginCookie.authCookie(request))
			response.sendRedirect("Login");
		else
		{
			String uid = LoginCookie.Get(request)[0];
			String fileName;
			
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);	
			String message = "Η φωτογραφία ανανεώθηκε με επιτυχία.";
			
			if(!isMultipart)
			{
				message = "Δεν επιλέχθηκε κάποια εικόνα.";				
			}
			else
			{					
				DiskFileItemFactory factory = new DiskFileItemFactory();
				
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setSizeMax(300*1024);
				
				try 
				{
					List<FileItem> items = upload.parseRequest(request);
					
					Iterator<FileItem> itr = items.iterator();
					
					while(itr.hasNext())
					{
						FileItem item = (FileItem)itr.next();
						
						if(!item.isFormField())
						{
						    fileName = "images/profilePictures/profpic_" + uid + 
						    				item.getName().substring(item.getName().lastIndexOf("."));						    
						   
						    ErrorCodes er = User.Edit(uid, new String[]{ "photo"}, new String[]{ "'" +  fileName + "'" });
						    if(er == ErrorCodes.OK)
						    {
							    File fu = new File(request.getServletContext().getRealPath(fileName));
							    
							    item.write(fu);
						    }
						    else
						    {
						    	throw new Exception();						    	
						    }
						}
						
					}
					
				}
				catch(FileUploadBase.SizeLimitExceededException slee)
				{
					message = "Το αρχείο που επιλέξατε είναι πολύ μεγάλο.";
					System.out.println("Upload file exception : " + slee.toString());					
				}
				catch (Exception e)
				{
					message = "Παρουσιάστηκε πρόβλημα κατα το ανέβασμα του αρχείου.";
					System.out.println("Upload file exception : " + e.toString());
				}
			}
		
			String[] msg = new String[]{"", message, "", ""};
			request.setAttribute("message", msg);
			RequestDispatcher rq = request.getRequestDispatcher("Profile");
			rq.forward(request, response);				
		}

	}

}